const path = require('path');
const fs = require('fs-extra');
const sharp = require('sharp');

const n = 1;
const inputDir = path.resolve(`./input${n}`);
const outputDir = path.resolve(`./output${n}`);
const output = path.resolve(outputDir, `${Date.now()}.jpg`);
const ImageController = require('./ImageController');

// 单张尺寸
const SINGLE_IMAGE_SIZE = {
  width: 1440,
  height: 1080
};

// 输出合并户型图尺寸
const MERGE_RESIZE = {
  width: 1440,
  height: 1080
};

// 图像控制器类
const imageController = new ImageController();

(async () => {
  // 开始
  await fs.ensureDir(inputDir);
  await fs.ensureDir(outputDir);

  const images = await fs.readdir(inputDir);

  const filelist = await Promise.all(images.map(async image => {
    const filepath = path.resolve(inputDir, image);
    const { width, height } = await imageController.getMetadata(filepath);

    return {
      width,
      height,
      filepath
    }
  }));

  fileListBuffer = await Promise.all(filelist.map(async (file, index, arr) => {
    const instance = await sharp(file.filepath);
    let buffer = await instance.toBuffer();
    // 文字
    const text = (index + 1) + '层';
    const { width, height } = await imageController.getMetadata(buffer);

    // 设置单张图片内间距，使整体展示效果更佳
    const padding = {
      top: Math.ceil(height * 0.02),
      bottom: Math.ceil(height * 0.02),
      left: Math.ceil(width * 0.02),
      right: Math.ceil(width * 0.02)
    }

    // 固定文字像素36
    const fontSize = 36

    // 拼接文字
    buffer = await imageController.mergeText(text, buffer, {
      fontSize,
      offset: fontSize * 1
    });

    // 切除空白区域
    buffer = await imageController.trim(buffer);

    // 扩展单张图外轮廓
    return await imageController.extend(buffer, { ...padding });
  }));

  // 合并所有图片
  let buffer = await imageController.merge2(fileListBuffer);

  await sharp(buffer).toFile(output);

  console.log('完成');
})()